package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.bean.ShoppingCart;
import com.itheima.common.BaseContext;
import com.itheima.dao.ShoppingCartDao;
import com.itheima.exception.CustomException;
import com.itheima.service.ShoppingCartService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author Tang
 * @date 2023/2/25
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartDao, ShoppingCart> implements ShoppingCartService {
    @Override
    public void addCart(ShoppingCart shoppingCart) {
        // 0.获取当前用户id
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            throw new CustomException("请先登录!");
        }
        
        // 1.查询购物车表是否已存在需要添加的商品  根据userId、菜品id（可能口味）或者套餐id 唯一确定一条数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        if (shoppingCart.getDishId() != null) { // 添加菜品  eg: 添加一个 辣子鸡 中辣，添加 辣子鸡  不辣  添加米饭
            wrapper.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
            wrapper.eq(shoppingCart.getDishFlavor() != null, ShoppingCart::getDishFlavor, shoppingCart.getDishFlavor());
        } else {                                // 添加套餐
            wrapper.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        ShoppingCart cart = this.getOne(wrapper);
        
        // 2.如果是新的商品，设置number数量为1，
        if (cart == null) {
            cart = shoppingCart;
            // 3.补齐字段：user_id、create_time
            cart.setNumber(1);
            cart.setUserId(userId);
            cart.setCreateTime(LocalDateTime.now());
        } else {
            // 4.如果不是新的商品，设置number数量+1
            cart.setNumber(cart.getNumber() + 1);
        }
        
        // 6.保存到购物车表中  【注意】需要调用更新或者新增方法
        this.saveOrUpdate(cart);
    }
    
    /**
     * 购物车订单减一
     *
     * @param shoppingCart
     */
    @Override
    public void sub(ShoppingCart shoppingCart) {
        // 根据前端传的菜品id或套餐id进行减1
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        // 获取菜品id，看是否存在，用于判断是菜品，还是套餐
        Long dishId = shoppingCart.getDishId();
        // 菜品id不为null,就是菜品
        if (dishId != null) {
            // 当同一菜品选择不同口味会无法判断  TUDO 待完善
            wrapper.eq(ShoppingCart::getDishId, dishId);
            
        } else {// 菜品为null就是套餐id
            wrapper.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        ShoppingCart cart = this.getOne(wrapper);
        Integer number = cart.getNumber();
        if (number > 1) {
            // 数量大于1就减1
            cart.setNumber(cart.getNumber() - 1);
            this.saveOrUpdate(cart);
        } else {
            // 当数量为1直接删除
            this.remove(wrapper);
        }
    }
}
